const utils = require("../../utils/util.js");
const cardCases = require("../../mock/data/cards.js");
Page({
  data: {
    cardId: "",
    groupsList: [],
    total: 0,
    showResult: false,
    showQuick: false,
    showTip: false,
    generatorCardImagePath: "", // 名片图片，用于保存默认名片图片
    quickDetail: {
      name: "",
      mobile: "",
      compName: "",
      position: "",
      email: "",
      address: ""
    },
    showShareButton: false,
    firstCardId: "",
    unFinished: false
  },
  showTips() {
    // 显示提示窗
    this.setData({
      showTip: true
    });
  },
  getGroupsList() {
    utils
      .ajax("/v1/bcs/queryUserCardGroups.do", {
        pageNo: 1,
        pageSize: 10
      })
      .then(res => {
        if (res.code === "000000") {
          let showShareButton = false,
            firstCardId = "";
          const storageMyCards = getApp().globalData.myCards;
          if (res.data.datas.length > 0) {
            showShareButton = true;
            firstCardId = storageMyCards[0].cardId;
          } else {
            console.log(getApp().globalData);
            if (storageMyCards.length > 0) {
              console.log("可以创建");
              showShareButton = true;
              firstCardId = storageMyCards[0].cardId;
            } else {
              console.log("不可以创建");
              showShareButton = false;
            }
          }
          this.setData({
            groupsList: res.data.datas || [],
            firstCardId,
            total: res.data.total,
            showShareButton,
            showResult: true
          });
        }else{
          console.log(res.message || "获取名片群列表失败");
        }
      })
      .catch(res => {});
  },
  hideTip() {
    // 关闭完善信息提示,点击知道了事件
    this.setData({
      showTip: false,
      unFinished: false
    });
  },
  showWrite() {
    // 显示快速完善资料面板，点击了去完善按钮
    this.setData({
      showTip: false,
      showQuick: true
    });
  },
  onInputChange(event) {
    // 更新输入框内容
    let key = event.target.dataset.key;
    let value = event.detail.value.trim();
    this.setData(
      {
        ["quickDetail." + key]: value.trim()
      },
      () => {}
    );
  },
  detectGroupInfo(res) {
    // 创建微信名片群
    utils
      .ajax("/v1/bcs/createUserCardGroup.do", {
        cardId: this.data.firstCardId,
        encryptedData: res.encryptedData,
        iv: res.iv
      })
      .then(res => {
        wx.hideLoading();
        if (res.code === "000000") {
          wx.navigateTo({
            url:
              "/pages/group/group?id=" +
              res.data.groupId +
              "&wid=" +
              res.data.wxGroupId
          });
          getApp().globalData["shareTicket"] = ""; // 分享过来的shareTicket，用过之后立马清空
        }else{
          console.log(res.message || "获取群信息失败");
        }
      })
      .catch(res => {
        wx.hideLoading()
      });
  },
  getUserInfo(e) {
    if (e.detail.userInfo) {
      getApp().globalData["avatarUrl"] = e.detail.userInfo.avatarUrl;
      getApp().globalData["nickName"] = e.detail.userInfo.nickName;
      this.saveQuickInfo();
    } else {
      utils.message("必须通过授权才能保存当前名片");
    }
  },
  saveQuickInfo(res) {
    // 保存快速完善名片信息
    const _this = this;
    const checkOptions = [
      {
        name: "姓名",
        key: "name"
      },
      {
        name: "手机号码",
        key: "mobile"
      },
      {
        name: "公司/单位名称",
        key: "compName"
      },
      {
        name: "职位",
        key: "position"
      },
      {
        name: "邮箱",
        key: "email"
      },
      {
        name: "地址",
        key: "address"
      }
    ];
    let flag = true;
    for (let i in checkOptions) {
      let item = this.data.quickDetail[checkOptions[i].key];
      if (item.length === 0) {
        utils.message(checkOptions[i].name + "不能为空");
        flag = false;
        return false;
      }
    }
    if (!flag) {
      return false;
    }
    // 按照默认模板生成图片

    wx.showLoading({
      mask: true,
      title: "正在保存..."
    });
    let detail = this.data.quickDetail;
    utils
      .generatorImage( this, {
        name: { value: detail.name },
        mobile: { value: detail.mobile },
        compName: { value: detail.compName },
        position: { value: detail.position },
        address: { value: detail.address },
        email: { value: detail.email }
      })
      .then(res => {
        console.log(res);
        utils
          .ajax(
            "/v1/bcs/uploadCustBusinessCard.do",
            {},
            {
              name: "businessCardFile",
              path: res.tempFilePath
            }
          )
          .then(res => {
            wx.hideLoading()
            if (res.code === "000000") {
              // 图片上传成功
              _this.setData({
                generatorCardImagePath: res.data.path
              });
              _this.saveRealData();
            } else {
              // 图片上传失败
              wx.hideLoading();
              utils.message(res.message || "图片上传失败");
            }
          })
          .catch(err => {
            wx.hideLoading();
          });
      })
      .catch(res => {
        wx.hideLoading()
        utils.message("生成图片失败，请稍后重试");
      });
  },
  saveRealData() {
    // 上传快速名片信息，
    const _this = this;
    const detail = this.data.quickDetail;
    const postData = {
      name: detail.name,
      mobile: detail.mobile,
      compName: detail.compName,
      position: detail.position,
      address: detail.address,
      mail: detail.email,
      avatarUrl: getApp().globalData["avatarUrl"], // 	128	是	头像 wx.getUserInfo中获得
      customerPicturePath: this.data.generatorCardImagePath
    };
    utils
      .ajax("/v1/bcs/createUserCard.do", postData)
      .then(res => {
        
        wx.hideLoading();
        if (res.code === "000000") {
          _this.setData({
            showQuick: false,
            showShareButton: true
          });
          if (this.data.unFinished) {
            // 如果有未完成的任务，这里指的是从卡片中进入页面，保存信息后自动创建群
            this.setData({
              firstCardId: res.data.cardId
            });
            wx.getShareInfo({
              shareTicket: getApp().globalData.shareTicket,
              success(res) {
                _this.detectGroupInfo(res);
              },
              fail(res) {
                wx.hideLoading();
                console.log(res);
              }
            });
          } else {
            utils.message("保存成功，快去创建名片群吧");
          }
        } else {
          utils.message(res.message || '快速保存失败')
          console.log(res.message||'快速保存失败')
        }
      })
      .catch(res => {
        wx.hideLoading();
      });
  },
  onLoad: function() {},
  onReady() {
    wx.showShareMenu({
      withShareTicket: true
    });
  },
  onShow() {
    const _this = this;
    utils
      .preGet()
      .then(res => {
        if (getApp().globalData.scene == "1044") {
          this.dealShare();
        } else {
          this.getGroupsList();
        }
      })
      .catch(res => {});
  },
  dealShare(){
    const _this = this;
    console.log("从分享进来");
    getApp().globalData["scene"] = "1001";
    // 如果来源于按钮分享，且没有名片的话，直接显示创建名片
    const storageMyCards = getApp().globalData.myCards;
    console.log('getApp().globalData',getApp().globalData);
    if (storageMyCards.length == 0) {
      console.log('用户还未创建名片，任务挂起，先创建名片')
      this.setData({
        showResult: true,
        showTip: true,
        unFinished: true
      });
    } else {
      this.setData({
        firstCardId: getApp().globalData["myCards"][0].cardId
      });
      let shareTicket = getApp().globalData["shareTicket"];
      if (!shareTicket) {
        wx.navigateTo({
          url: "/pages/index/index"
        });
        console.log("shareTicket未找到");
      }
      console.log(shareTicket);
      // 只有在群聊中打开才会有这个属性
      wx.getShareInfo({
        shareTicket: shareTicket,
        success(res) {
          console.log(1);
          wx.showLoading({
            mask: true,
            title: "正在识别名片..."
          });
          _this.detectGroupInfo(res);
        },
        fail(res) {
          console.log(res);
        }
      });
    }
  },
  onShareAppMessage(res) {
    let _this = this;
    if (res.from == "button") {
      return {
        title: "快名片助手",
        path: "/pages/groups/groups",
        success(res) {
          console.log(res);
          if (res.shareTickets && res.shareTickets.length > 0) {
            wx.getShareInfo({
              shareTicket: res.shareTickets[0],
              success(res) {
                _this.detectGroupInfo( res);
              }
            });
          }
        }
      };
    } else {
      return {
        title: "快名片助手",
        path: "/pages/index/index"
      };
    }
  },
  hideQuick() {
    this.setData({
      showQuick: false
    });
  }
});
